package com.foreknow.dao.impl;

import com.foreknow.dao.GuestbookDao;
import com.foreknow.db.DBManager;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.GuestBook;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDAO implements GuestbookDao {
    @Override
    public boolean save(GuestBook gb) throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        int insert = jdbcTemplate.update("insert into guestbook(name,phone,email,title,content) values(?,?,?,?,?)", gb.getName(), gb.getPhone(), gb.getEmail(), gb.getTitle(), gb.getContent());
        return insert==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        EntityMapping EM = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> query = jdbcTemplate.query("select * from guestbook",EM);
        return query;
    }

    @Override
    public GuestBook getQueryById(int id) throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        EntityMapping EM = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query("select * from guestbook where id=?", EM,id);
        if (list.size()>0){
            GuestBook gb=(GuestBook) list.get(0);
            return gb;
        }
        return null;
    }

    @Override
    public boolean deleteById(int id) throws SQLException {
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        int delete = jdbcTemplate.update("delete from guestbook where id=?", id);
        return delete==1;
    }

}
